package com.twinkle.rpc.common.serializer.myserializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twinkle.rpc.common.message.RpcRequest;
import com.twinkle.rpc.common.message.RpcResponse;

/**
 * fastjson的序列化方式
 */
public class JsonSerializer implements Serializer{
    @Override
    public byte[] serialize(Object obj) {
        if (obj == null) {
            throw new IllegalArgumentException("序列化的对象为null");
        }
        return JSONObject.toJSONBytes(obj);
    }

    @Override
    public Object deserialize(byte[] bytes, int messageType) {
        if (bytes == null || bytes.length == 0) {
            throw new IllegalArgumentException("序列化的字节数组为null");
        }
        Object obj = null;
        // 传输的消息分为request与response
        switch (messageType){
            case 0:
                RpcRequest request = JSON.parseObject(bytes, RpcRequest.class);
                if (request.getParams() == null || request.getParamsType() == null) {
                    throw new IllegalArgumentException("Request params 为 null");
                }
                Object[] objects = new Object[request.getParams().length];
                for (int i = 0; i < objects.length; i++) {
                    Class<?> paramsType = request.getParamsType()[i];
                    if (!paramsType.isPrimitive() && !paramsType.isInstance(request.getParams()[i])) {
                        if (request.getParams()[i] instanceof JSONObject) {
                            objects[i] = JSONObject.toJavaObject((JSONObject) request.getParams()[i], paramsType);
                        } else {
                            throw new IllegalArgumentException("异常的数据类型，下标为： " + i);
                        }
                    } else {
                        objects[i] = request.getParams()[i];
                    }
                }
                request.setParams(objects);
                obj = request;
                break;

            case 1: // RpcResponse
                RpcResponse response = JSON.parseObject(bytes, RpcResponse.class);
                if (response.getData() != null) {
                    Class<?> dataType = response.getDataType();
                    if (!dataType.isInstance(response.getData())) {
                        if (response.getData() instanceof JSONObject) {
                            response.setData(JSONObject.toJavaObject((JSONObject) response.getData(), dataType));
                        } else {
                            throw new IllegalArgumentException("异常的数据类型: " + response.getData().getClass());
                        }
                    }
                }
                obj = response;
                break;

            default:
                System.out.println("不支持的数据类型: " + messageType);
                throw new RuntimeException("不支持的数据类型:  " + messageType);
        }
        return obj;
    }

    @Override
    public int getType() {
        return 1;
    }
}
